const ADMINPASS = "django";
const startDate = new Date();
/**
 * Logs the user in
 * Checks the DB to see if the name equals the password, if user doesn't exist, create a new one..
 */
function userLogin() {
    //Collect form information
    var firstName = $('#inputFirstName').val();
    var lastName = $('#inputLastName').val();
    var password = $('#inputPassword').val();
    var fullName = capitalizeName(firstName, lastName);

    var request = false;
    var result = null;
    var html = "";
    request = new XMLHttpRequest();
    if (request) {
        request.open("GET", "/login/" + fullName + "/" + password);
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {
                result = JSON.parse(request.responseText);
                if (result) {
                    //Put his name in the localstorage
                    localStorage.setItem('name', fullName);
                    window.location.href = './gameLogin.html';

                } else {
                    //Name of password is not correct!
                    alert("Username/Password is not correct! Try Again");
                }
            }
        };

        request.setRequestHeader('content-type', 'text/plain');
        request.send(null);
    }
}

/**
 * IF the user pressed the signup button - send him to the tournament bets and THEN to index.html
 */
function userSignup() {
    //Collect form information
    var firstName = $('#inputFirstName').val();
    var lastName = $('#inputLastName').val();
    var password = $('#inputPassword').val();

    if (firstName.length < 2 || lastName < 2) {
        //Illegal name, too short
        alert("Name too short");
    } else {

        var fullName = capitalizeName(firstName, lastName);

        var request = false;
        var result = null;
        var html = "";
        //var fullName = firstName + " " + lastName;
        request = new XMLHttpRequest();
        if (request) {
            request.open("GET", "./signup/" + fullName + "/" + password);
            request.onreadystatechange = function() {
                if (request.readyState == 4 && request.status == 200) {

                    result = JSON.parse(request.responseText);

                    if (result) {
                        //Put his name in the localstorage
                        localStorage.setItem('name', fullName);
                        window.location.href = './gameLogin.html';

                    } else {
                        //Error signing up - maybe this user exists already?
                        alert("This user already exists - please Login");
                    }
                }
            };

            request.setRequestHeader('content-type', 'text/plain');
            request.send(null);
        }

    }

}

/**
 * Forgot password function
 */
function forgotPassword() {
    var firstName = $('#inputFirstName').val();
    var lastName = $('#inputLastName').val();
    if (firstName == null || lastName == null) {
        alert("Please put in first and last name to get your password");
    } else {
        //User has put in a name and password
        var fullName = capitalizeName(firstName, lastName);
        var request = false;
        var result = null;
        var html = "";
        request = new XMLHttpRequest();
        if (request) {
            //Response is true if team created - false otherwise
            request.open("GET", "./userFetchPassword/" + fullName);
            request.onreadystatechange = function() {
                if (request.readyState == 4 && request.status == 200) {

                    result = JSON.parse(request.responseText);

                    if (result) {
                        //Put his name in the localstorage
                        localStorage.setItem('collection', newGroupName);

                        //Send to index
                        window.location.href = './index.html';

                    } else {
                        //Error creating team name - maybe team exists??
                        alert("No such User - please contact us at: oreporan@gmail.com");

                    }
                }
            };

            request.setRequestHeader('content-type', 'text/plain');
            request.send(null);
        }

    }
}

/**
 * Fixes the name
 */
function capitalizeName(first, last) {
    first = first.toLowerCase();
    last = last.toLowerCase();
    var firstCorrect = first.charAt(0).toUpperCase() + first.slice(1);
    var lastCorrect = last.charAt(0).toUpperCase() + last.slice(1);

    return firstCorrect + " " + lastCorrect;
}

/**
 * Creates a new group , puts in the user's local storage and adds a option to #mondialGroupSelect
 */
function signupCollection() {
    var username = localStorage.getItem('name');
    var newGroupName = $('#inputNewCollectionName').val();
    var i_pass = $('#inputAdminPassword').val();
    var collectionPass = $('#inputNewCollectionPassword').val();

    var request = false;
    var result = null;
    var html = "";
    request = new XMLHttpRequest();
    if (request) {
        //Response is true if team created - false otherwise
        request.open("GET", "./collectionSignup/" + username + "/" + newGroupName + "/" + collectionPass);
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {

                result = JSON.parse(request.responseText);

                if (result) {
                    //Put his name in the localstorage
                    localStorage.setItem('collection', newGroupName);

                    //Send to index
                    window.location.href = './index.html';

                } else {
                    //Error creating team name - maybe team exists??
                    alert("Team name exist - choose another");

                }
            }
        };

        request.setRequestHeader('content-type', 'text/plain');
        request.send(null);
    }

}

/**
 * Logs in this collection - check if user belongs to this collection and puts in the localstorage
 */
function loginCollection() {
    var username = localStorage.getItem('name');
    var collectionName = $('#mondialGroupSelect option:selected').text();
    var collectionPassword = $('#inputOldCollectionPassword').val();
    //User is sure
    request = new XMLHttpRequest();
    if (request) {
        //Response is true if team created - false otherwise
        request.open("GET", "./collectionLogin/" + username + "/" + collectionPassword + "/" + collectionName);
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {

                result = JSON.parse(request.responseText);

                if (result) {
                    //Put his name in the localstorage
                    localStorage.setItem('collection', collectionName);

                    //Send to index
                    window.location.href = './index.html';

                } else {
                    //Error logging in  team - maybe team exists??
                    alert("Wrong password - is this your group!?");

                }
            }
        };

        request.setRequestHeader('content-type', 'text/plain');
        request.send(null);
    }

}

/**
 * Fetches the collection list and puts in the #mondialGroupSelect
 */
function getCollections() {
    var request = false;
    var result = null;
    request = new XMLHttpRequest();
    if (request) {
        request.open("GET", "./collectionsFetch/");
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200) {

                result = JSON.parse(request.responseText);

                if (result == null) {
                    //Big Problem! atleast should be an empty array

                } else {
                    //List them in the <option>
                    for (var i = 0; i < result.length; i++) {
                        $('#mondialGroupSelect').append("<option>" + result[i].name + "</option>");

                    };
                }
            }
        };

        request.setRequestHeader('content-type', 'text/plain');
        request.send(null);
    }
}

//Right off the bat
$(document).ready(function() {
    getCollections();
});
